package com.sp2p.action.front;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Date;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gofull.gateway.wechat.config.WechatConfig;
import com.llpay.client.conn.HttpRequestSimple;
import com.llpay.client.utils.LLPayUtil;
import com.shove.config.LianpayConfig;
import com.shove.util.EncryptUtils;
import com.shove.util.MessageUtils;
import com.sp2p.entity.TextMessage;
import com.sp2p.entity.NewsMessage;
import com.sp2p.entity.Article;
import java.io.PrintWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class WchatMsgAction extends BaseFrontAction {
	public static Log log = LogFactory.getLog(WchatAction.class);
	private static final long serialVersionUID = 1L;
	
	public void wchatInterface() throws Exception {
		String method = request().getMethod();
		boolean isPostMethod = "POST".equalsIgnoreCase(method);
		
		if(isPostMethod){
			wchatInterfacePost();
		}else{
			wchatInterfaceGet();
		}
	}
	
	public void wchatInterfaceGet() throws Exception {

		String signature = request().getParameter("signature");
		String timestamp = request().getParameter("timestamp");
		String nonce = request().getParameter("nonce");
		String echostr = request().getParameter("echostr");

		// 将token、timestamp、nonce三个参数进行字典序排序
		String[] strarray = new String[] { WechatConfig.TOKEN, timestamp, nonce };
		Arrays.sort(strarray);
		StringBuilder content = new StringBuilder();
		for (String s : strarray) {
			content.append(s);
		}

		// 将三个参数字符串拼接成一个字符串进行sha-1加密，并与signature对比,如果相同返回echostr
		if (EncryptUtils.sha(content.toString().trim()).equals(signature)) {
			response().getWriter().print(echostr);
		}

	}
	
	public void wchatInterfacePost() throws Exception {
//		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
//        request().setCharacterEncoding("UTF-8");
//        response().setCharacterEncoding("UTF-8");
//
//        // 调用核心业务类接收消息、处理消息
//        String respMessage = this.processRequest();
//
//        System.out.println("推送出去的信息为:"+respMessage);
//
//        // 响应消息
//        PrintWriter out = response().getWriter();
//        out.print(respMessage);
//        out.close();
	}
	

    
	
	 /**
     * 处理微信发来的请求
     * @param request
     * @return
     */
    public  String processRequest() {

        String respMessage = null;
        String fromUserName = null;
        String toUserName = null;
        String  content =null;
        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtils.parseXml(request());

            System.out.println("接收到的信息为:"+requestMap);

            // 发送方帐号（open_id）
             fromUserName = requestMap.get("FromUserName");
            // 公众帐号
             toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            //消息内容
            content = requestMap.get("Content");

            // 事件推送
           if(msgType.equals(MessageUtils.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get("Event");
                // 订阅
                if (eventType.equals(MessageUtils.EVENT_TYPE_SUBSCRIBE)) {
                    respMessage =  getSubscribe(fromUserName,toUserName);
                }
                // 取消订阅
                else if (eventType.equals(MessageUtils.EVENT_TYPE_UNSUBSCRIBE)) {

                }
                else{
                    respMessage =  getSubscribe(fromUserName,toUserName);
                }
            }
            else if (msgType.equals(MessageUtils.REQ_MESSAGE_TYPE_TEXT)) {
               //respMessage =  getRespMovieMessage(content,fromUserName,toUserName);
            	respMessage =  getSubscribe(fromUserName,toUserName);

            }
            else{
               // 默认回复此文本消息
               TextMessage textMessage = new TextMessage();
               textMessage.setToUserName(fromUserName);
               textMessage.setFromUserName(toUserName);
               textMessage.setCreateTime(new Date().getTime());
               textMessage.setMsgType(MessageUtils.RESP_MESSAGE_TYPE_TEXT);
               textMessage.setFuncFlag(0);
               // 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
               textMessage.setContent("对不起，暂时还不懂你的意思噢！");
               // 将文本消息对象转换成xml字符串
               respMessage = MessageUtils.textMessageToXml(textMessage);
           }

        }
        catch (Exception e){
            // 默认回复此文本消息
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(new Date().getTime());
            textMessage.setMsgType(MessageUtils.RESP_MESSAGE_TYPE_TEXT);
            textMessage.setFuncFlag(0);
            // 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
            textMessage.setContent("请求处理异常，请稍候尝试！");
            // 将文本消息对象转换成xml字符串
            respMessage = MessageUtils.textMessageToXml(textMessage);
        }
        return respMessage;
    }

    /**
     * 订阅消息
     * @return
     */
    public String getSubscribe(String fromUserName,String toUserName){

        String respMessage = null;
        // 创建图文消息
        NewsMessage newsMessage = new NewsMessage();
        newsMessage.setToUserName(fromUserName);
        newsMessage.setFromUserName(toUserName);
        newsMessage.setCreateTime(new Date().getTime());
        newsMessage.setMsgType(MessageUtils.RESP_MESSAGE_TYPE_NEWS);
        newsMessage.setFuncFlag(0);

        List<Article> articleList = new ArrayList<Article>();

        StringBuffer sb = new StringBuffer();
        sb.append("共富理财就是时尚生活！");

        Article article = new Article();
        article.setTitle("邀您加入共富网，共富理财就享时尚生活");
        article.setDescription(sb.toString());
        article.setPicUrl("https://tegqbw.sn2.livefilestore.com/y2pjSLQxAtPCQZeKeKBS8UjEgluTl4nI0nwODqnUPn6sXypqpaYUnwHnDuiKKXkiwxR3ejnsT5He1DcfEVxW8uP9svIY3C7Tuk7478XwbvOEa5X9AjOqdngDUVjqjjOCnMn/knuttz-ueba-305111.jpg?psid=1");
        article.setUrl("http://www.gofull.com.cn/wchatLinks.do");
        articleList.add(article);
        // 设置图文消息个数
        newsMessage.setArticleCount(articleList.size());
        // 设置图文消息包含的图文集合
        newsMessage.setArticles(articleList);
        // 将图文消息对象转换成xml字符串
        respMessage = MessageUtils.newsMessageToXml(newsMessage);

        return respMessage;
    }

   
}
